const {
	db,
	dbCmd,
	result_success,
	result_error,
	appletInfoCollection,
	shopieCollection
} = require('../../common/constants')
const {
	mainSpaceId
} = require('config-main-space')
const mycloud = uniCloud.init({
	provider: 'tencent',
	spaceId: mainSpaceId
})
const wmzWechatSdk = uniCloud.importObject('wmz-wechat-sdk')
const wmzAlipaySdk = uniCloud.importObject('wmz-alipay-sdk')
module.exports = async function(params = {}) {
	const token = this.getUniIdToken()
	if (!token) {
		return result_error('登录失效,请重新登录')
	}
	let payload = await this.uniID.checkToken(token)
	if (payload.code) {
		return payload
	}
	let id = params.id
	let type = params.type
	let shopieData = await shopieCollection.doc(id).get()
	shopieData = shopieData.data[0]
	let way = shopieData.way
	let app_id = shopieData.app_id
	let appletInfo = await db.collection('wmz-applet-info').doc(app_id).get()
	appletInfo = appletInfo.data[0]
	if (type === 'yj') {
		if (shopieData.yj_refound) {
			return result_error('押金已退')
		}
		let yj_money = shopieData.yj_money
		if (!yj_money) {
			return result_error('收支无押金')
		}
		let money = shopieData.money
		let mchid = appletInfo.wechat.mchid
		let sub_mchid = appletInfo.wechat.sub_mchid
		let transaction_id = shopieData.order_no
		let out_refund_no = new Date().getTime() + ""
		if (way === '支付宝支付') {
			let params = {
				app_id: app_id,
				url: 'alipay.trade.refund',
				biz_content: {
					trade_no: shopieData.order_no,
					refund_amount: (yj_money / 100).toFixed(2),
					refund_reason: '退押金',
					out_request_no :out_refund_no
				}
			}
			res = await wmzAlipaySdk.alipayRequestCommon(params)
			if (res.code === 200) {
				let shopie = {
					app_id: app_id,
					shop_id: app_id,
					order_no: shopieData.order_no,
					title: "退押金",
					cate: '退款',
					way: shopieData.way,
					type: 1,
					money: yj_money,
					out_refund_no: out_refund_no,
					creator_id: payload.uid,
					create_time: new Date().getTime(),
					share_user_id:shopieData.share_user_id
				};
				await db.collection('wmzmall-shopie').add(shopie);
				let refound_data = shopieData.refound_data
				let tRefound_money = shopieData.refound_money
				if (refound_data) {
					refound_data.push(shopie)
				} else {
					refound_data = [shopie]
				}
				if (tRefound_money) {
					tRefound_money = tRefound_money + refound_money
				} else {
					tRefound_money = yj_money
				}
				shopieCollection.doc(id).update({
					yj_refound: true,
					refound_money: tRefound_money,
					refound_data: refound_data
				})
				return result_success()
			} else {
				if (res.msg.code === 'INVALID REQUEST') {
					return result_error('申请退款金额超过订单可退金额')
				} else {
					return result_error(res.msg)
				}
			}
		} else {
			try{
				let add=await wmzWechatSdk.add()
				console.log(add)
			}catch(e){
				console.log(123)
				console.log(e)
			}
			let wechatpaySerial, certificates
			if (!wechatpaySerial) {
				let v3Certificates = await wmzWechatSdk.v3Certificates(mchid)
				if (v3Certificates.code === 200) {
					certificates = v3Certificates.data.certificate
					wechatpaySerial = v3Certificates.data.serial_no
				}
			}
			let data = {
				sub_mchid: sub_mchid,
				transaction_id: transaction_id,
				out_refund_no: out_refund_no,
				reason: '押金',
				amount: {
					refund: yj_money,
					total: money,
					currency: 'CNY'
				}
			}
			let url = "https://api.mch.weixin.qq.com/v3/refund/domestic/refunds"
			let author = await wmzWechatSdk.signAuthorV3(mchid, "POST", url, data)
			if (author.code === 200) {
				author = author.data
			} else {
				return result_error("author签名异常！")
			}
			let res = await wmzWechatSdk.wechatRequestCommon({
				url: url,
				headers: {
					"authorization": author,
					"Wechatpay-Serial": wechatpaySerial
				},
				data: data
			})
			if (res.code === 200) {
				let shopie = {
					app_id: app_id,
					shop_id: app_id,
					order_no: shopieData.order_no,
					title: "退押金",
					cate: '退款',
					way: shopieData.way,
					type: 1,
					money: yj_money,
					out_refund_no: out_refund_no,
					creator_id: payload.uid,
					create_time: new Date().getTime(),
					share_user_id:shopieData.share_user_id
				};
				await db.collection('wmzmall-shopie').add(shopie);
				let refound_data = shopieData.refound_data
				let tRefound_money = shopieData.refound_money
				if (refound_data) {
					refound_data.push(shopie)
				} else {
					refound_data = [shopie]
				}
				if (tRefound_money) {
					tRefound_money = tRefound_money + refound_money
				} else {
					tRefound_money = yj_money
				}
				shopieCollection.doc(id).update({
					yj_refound: true,
					refound_money: tRefound_money,
					refound_data: refound_data
				})
				return result_success()
			} else {
				if (res.msg.code === 'INVALID REQUEST') {
					return result_error('申请退款金额超过订单可退金额')
				} else {
					return result_error(res.msg)
				}
			}
		}
	} else {
		let refound_money = params.refound_money * 100
		let money = shopieData.money
		if (!refound_money) {
			return result_error('退款金额不能为空')
		}
		if (refound_money > money) {
			return result_error('退款金额大于收款金额')
		}
		let mchid = appletInfo.wechat.mchid
		let sub_mchid = appletInfo.wechat.sub_mchid
		let transaction_id = shopieData.order_no
		let out_refund_no = new Date().getTime() + ""
		if (way === '支付宝支付') {
			let params = {
				app_id: app_id,
				url: 'alipay.trade.refund',
				biz_content: {
					trade_no: shopieData.order_no,
					refund_amount: (refound_money / 100).toFixed(2),
					refund_reason: '部分退款',
					out_request_no :out_refund_no
				}
			}
			res = await wmzAlipaySdk.alipayRequestCommon(params)
			if (res.code === 200) {
				let shopie = {
					app_id: app_id,
					shop_id: app_id,
					order_no: shopieData.order_no,
					way: shopieData.way,
					title: "部分退",
					cate: '退款',
					type: 1,
					money: refound_money,
					out_refund_no: out_refund_no,
					creator_id: payload.uid,
					create_time: new Date().getTime(),
					share_user_id:shopieData.share_user_id
				};
				let refound_data = shopieData.refound_data
				let tRefound_money = shopieData.refound_money
				if (refound_data) {
					refound_data.push(shopie)
				} else {
					refound_data = [shopie]
				}
				if (tRefound_money) {
					tRefound_money = tRefound_money + refound_money
				} else {
					tRefound_money = refound_money
				}
				await db.collection('wmzmall-shopie').add(shopie);
				shopieCollection.doc(id).update({
					yj_refound: true,
					refound_money: tRefound_money,
					refound_data: refound_data
				})
				return result_success()
			} else {
				if (res.msg.code === 'INVALID REQUEST') {
					return result_error('申请退款金额超过订单可退金额')
				} else {
					return result_error(res.msg)
				}
			}
		} else {
			let wechatpaySerial, certificates
			if (!wechatpaySerial) {
				let v3Certificates = await wmzWechatSdk.v3Certificates(mchid)
				if (v3Certificates.code === 200) {
					certificates = v3Certificates.data.certificate
					wechatpaySerial = v3Certificates.data.serial_no
				}
			}
			let data = {
				sub_mchid: sub_mchid,
				transaction_id: transaction_id,
				out_refund_no: out_refund_no,
				reason: '部分退',
				amount: {
					refund: refound_money,
					total: money,
					currency: 'CNY'
				}
			}
			let url = "https://api.mch.weixin.qq.com/v3/refund/domestic/refunds"
			let author = await wmzWechatSdk.signAuthorV3(mchid, "POST", url, data)
			if (author.code === 200) {
				author = author.data
			} else {
				return result_error("author签名异常！")
			}
			let res = await wmzWechatSdk.wechatRequestCommon({
				url: url,
				headers: {
					"authorization": author,
					"Wechatpay-Serial": wechatpaySerial
				},
				data: data
			})
			if (res.code === 200) {
				let shopie = {
					app_id: app_id,
					shop_id: app_id,
					order_no: shopieData.order_no,
					way: shopieData.way,
					title: "部分退",
					cate: '退款',
					type: 1,
					money: refound_money,
					out_refund_no: out_refund_no,
					creator_id: payload.uid,
					create_time: new Date().getTime(),
					share_user_id:shopieData.share_user_id
				};
				let refound_data = shopieData.refound_data
				let tRefound_money = shopieData.refound_money
				if (refound_data) {
					refound_data.push(shopie)
				} else {
					refound_data = [shopie]
				}
				if (tRefound_money) {
					tRefound_money = tRefound_money + refound_money
				} else {
					tRefound_money = refound_money
				}
				await db.collection('wmzmall-shopie').add(shopie);
				shopieCollection.doc(id).update({
					yj_refound: true,
					refound_money: tRefound_money,
					refound_data: refound_data
				})
				return result_success()
			} else {
				if (res.msg.code === 'INVALID REQUEST') {
					return result_error('申请退款金额超过订单可退金额')
				} else {
					return result_error(res.msg)
				}
			}
		}
	}
	return result_error()
}